package controllers;

import helpers.HeaderHelper;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import java.util.regex.Matcher;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;

public class ContactUsServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		//set Header
		HeaderHelper headerHelper = new HeaderHelper();
		String[] check = new String[4];
		
		//Check domain exists
		response.setHeader( "Cache-Control", "public, max-age=2592000");
		response.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
		
		//Set header content
		headerHelper.setTitle(request.getServerName() + " - Contact Us");
		headerHelper.setOgtitle(request.getServerName() + " - Contact Us");
		
		request.setAttribute("headerHelper", headerHelper);
		request.setAttribute("check", check);
		try {
			request.getRequestDispatcher("/pages/contact_us.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		//Set header page
        HeaderHelper headerHelper = new HeaderHelper();
        String[] check = new String[4];
        
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
        
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String text = request.getParameter("message");

        String msgBody = text;
        
        if(name == null || (name != null && name.equals("")))
		{
			check[0] = "Name is not empty";
		}
		java.util.regex.Pattern p = java.util.regex.Pattern.compile(".+@.+\\.[a-z]+");
		Matcher m = p.matcher(email);
		boolean matchFound = m.matches();
		
		if (!matchFound)
		{
			check[1] = "Invalid Email";
		}
		if(text == null || (text != null && text.equals("")))
		{
			check[2] = "Message is not empty";
		}
		        
		String remoteAddr = request.getRemoteAddr();
		ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
		reCaptcha.setPrivateKey("6LedsNASAAAAAK4M4Y71Uloy8LWgNBff0H_E6L0V");
		
		String challenge = request.getParameter("recaptcha_challenge_field");
		String uresponse = request.getParameter("recaptcha_response_field");
		if(challenge == null)
		{
		        challenge = "b";
		}
		if(uresponse == null)
		{
		        uresponse = "a";
		}
		
		ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);
		
		if (!reCaptchaResponse.isValid()) {
		        check[3] = "Invalid Capchar";
		}
		        
		if(check[0] == null && check[1] == null && check[2] == null && check[3] == null)
        {
                try {
                        Message msg = new MimeMessage(session);
                        msg.setFrom(new InternetAddress("admin@domainworlds.net", email));
                        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
                                        "admin@domainworlds.net", email));
                        msg.setSubject("Mail contact from " + name);
                        msg.setText(msgBody);
                        Transport.send(msg);

                } catch (AddressException e) {
                        // ...
                } catch (MessagingException e) {
                        // ...
                }
                request.setAttribute("success", "Thanks for your contact");
        }
		
		//Set header content
		headerHelper.setTitle(request.getServerName() + " - Contact Us");
		headerHelper.setOgtitle(request.getServerName() + " - Contact Us");
		request.setAttribute("check", check);
		request.setAttribute("headerHelper", headerHelper);
		        try {
		                request.getRequestDispatcher("/pages/contact_us.jsp").forward(request, response);
		        } catch (Exception e) {
		                e.printStackTrace();
		        }
	}
}
